
const { resolve } = require('dns');
var path=require('path');
var db=require('../database/index.js');
const { append } = require('../database/warehouse_merchants.js');

//读取所有商户 商品
function readList(){
	return new Promise(async (resolve,reject)=>{
		//读取商家列表
		var business=await db.merchants.findAll()
		var arr=[]
		if(business instanceof Array)
			business.forEach(item=>{
				arr.push({
					id:item._id,
				})
			})
		business=arr
		//读取所有 数据表	
		var list=[]
		business.forEach(async (item,index)=>{
			var result= await db.merchants.warehouse.getDate(item.id)
			if(result){
				result.commodity.forEach((commodity,index1)=>{
					list.push({
						_id:String(index+item.id+index1),
						title:commodity.title,//商品名
						classes:commodity.genre,//类别
						price:commodity.price,//价格
						salesVolume:commodity.sales_volume,//销量
						img:commodity.images[0],//展示图
						businessName:result.StoreName,//商家店名
						businessID:item.id,//商家Id
						index:index1
					})
				})
			}
			if(index==business.length-1){
				resolve(list);
			}
		})
	})
}
function update(){
	return new Promise(async (resolve,reject)=>{
		var result= await readList()
		result.sort((a,b)=>{
			return b.salesVolume - a.salesVolume
		})
		//清空数据库
		var isRemove=await db.goods.remove()
		result.forEach(async (item,index)=>{
			var apend=await db.goods.update(item)
		})
		resolve(result.length)
	})
}

function find(start,end=1){
	return new Promise(async (resolve,reject)=>{
		resolve(db.goods.find(start,end))
	})
};

module.exports={
	update,
	find
}